package com.example.makerspace.factory;



import com.alibaba.fastjson.JSON;

import java.net.HttpURLConnection;

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;



import java.io.*;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import java.rmi.Remote;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;



public  class testThreadPoolFactory implements ThreadFactory {


    private AtomicInteger threadIdx = new AtomicInteger(0);

    private String threadNamePrefix;

    public testThreadPoolFactory(String Prefix) {
        threadNamePrefix = Prefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName(threadNamePrefix + "-xxljob-" + threadIdx.getAndIncrement());
        return thread;
    }

  public static void time() throws ParseException {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


      String start_date="2024-6-7 12:0:0";
      String end_date="22024-6-8 12:0:0";

      Date date = new Date();
      String format = sdf.format(date);


      Date date_start = sdf.parse(start_date);
      Date today = sdf.parse(format);
      Date date_end = sdf.parse(end_date);


      long startTimeMs = date_start.getTime();
      long endTimeMs = date_end.getTime();
      long time = today.getTime();

      if(time>=startTimeMs){
          System.out.println("小皮成功参与秒杀!");
      }else{
          System.out.println("小皮错过秒杀!");
      }
  }      /**
     * 从List<A> copy到List<B>
     * @param list List<B>
     * @param clazz B
     * @return List<B>
     */
    public static <T> List<T> copy(List<?> list,Class<T> clazz){
        String oldOb = JSON.toJSONString(list);
        return JSON.parseArray(oldOb, clazz);
    }

    /**
     * 从对象A copy到 对象B
     * @param ob A
     * @param clazz B.class
     * @return B
     */
    public static <T> T copy(Object ob,Class<T> clazz){
        String oldOb = JSON.toJSONString(ob);
        return JSON.parseObject(oldOb, clazz);
    }


    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
    }

    public static String sendGetRequestWithParameters(String baseUrl, String parameterName, String parameterValue, String parameterName2, String parameterValue2,
                                                    String parameterName3, String parameterValue3) {
        String responseBody="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String urlWithParameters = buildUrlWithMultipleParameters(baseUrl, parameterName, parameterValue,parameterName2,parameterValue2
            ,parameterName3,parameterValue3);
            HttpGet httpGet = new HttpGet(urlWithParameters);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                responseBody = EntityUtils.toString(entity);
                System.out.println(responseBody);
            } else {
                System.out.println("Request failed with status code: " + statusCode);
            }

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    public static String sendGetRequestWithParameters(String baseUrl) {
        String responseBody="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String urlWithParameters = buildUrlWithNoParameters(baseUrl);
            HttpGet httpGet = new HttpGet(urlWithParameters);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                responseBody = EntityUtils.toString(entity);
                System.out.println(responseBody);
            } else {
                System.out.println("Request failed with status code: " + statusCode);
            }

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
        return responseBody;
    }
    public static String buildUrlWithMultipleParameters(String baseUrl, String parameter1Name, String parameter1Value, String parameter2Name, String parameter2Value,
                                                        String parameterName3, String parameterValue3) throws URISyntaxException {
        URI uri = new URI(baseUrl);
        StringBuilder queryBuilder = new StringBuilder();
        queryBuilder.append(parameter1Name).append("=").append(parameter1Value);
        queryBuilder.append("&").append(parameter2Name).append("=").append(parameter2Value).append(parameterName3).append("=")
                .append(parameterValue3);
        URI uriWithParameters = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), queryBuilder.toString(), uri.getFragment());
        return uriWithParameters.toString();
    }
    public static String buildUrlWithNoParameters(String baseUrl) throws URISyntaxException {
        URI uri = new URI(baseUrl);
        StringBuilder queryBuilder = new StringBuilder();
        URI uriWithParameters = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), queryBuilder.toString(), uri.getFragment());
        return uriWithParameters.toString();
    }


        public static void uploadFile(String filePath, Socket socket) throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

            int byteRead;
            byte[] buffer = new byte[1024];
            while ((byteRead = bis.read(buffer))!= -1) {
                bos.write(buffer, 0, byteRead);
            }

            bos.flush();
            bis.close();
            bos.close();
        }

    // 递归上传文件夹
    private static void uploadFolder(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        uploadFolder(file); // 递归上传子文件夹
                    } else {
                        uploadFile(file); // 上传文件
                    }
                }
            }
        }
    }

    public static void unzipInputStream() {
        try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File("C:\\Users\\Lenovo\\Desktop\\sso\\yyy.zip")))) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zip.getNextEntry()) != null) {
                String fileName_zip = zipEntry.getName();
                System.out.println(fileName_zip);
                File file = new File("C:\\Users\\Lenovo\\Desktop\\sso\\yyy.zip\\" + fileName_zip);
                if (fileName_zip.endsWith("/")) {
                    file.mkdir();
                } else {
                    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] byte_s = new byte[1024];
                    int num;
                    while ((num = zip.read(byte_s, 0, byte_s.length)) > 0) {
                        outputStream.write(byte_s, 0, num);
                    }
                    outputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 上传单个文件
    private static void uploadFile(File file) {
        String uploadUrl = "127.0.0.1"; // 替换为你的上传 URL

        try (FileInputStream inputStream = new FileInputStream(file)) {
            HttpURLConnection connection = (HttpURLConnection) new URL(uploadUrl).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("File-Name", file.getName());

            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Uploaded " + file.getName() + ": " + responseCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static void unzip(String zipFilePath, String destinationDirectory) throws IOException {
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            File file = new File(destinationDirectory + File.separator + entryName);

            if (entry.isDirectory()) {
                file.mkdirs();
                continue;
            }

            try (InputStream inputStream = zipFile.getInputStream(entry);
                 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {

                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
            }
        }

        zipFile.close();
    }
        public static double getFolderSizeInMB(File folder) {
            long sizeInBytes = 0;
            File[] files = folder.listFiles();
            if (files!= null) {
                for (File file : files) {
                    if (file.isFile()) {
                        sizeInBytes += file.length();
                    } else if (file.isDirectory()) {
                        sizeInBytes += getFolderSizeInMB(file);
                    }
                }
            }
            double sizeInMB = sizeInBytes / (1024.0);
            return sizeInMB;
        }




        public static boolean checkFileExistsInFolder(String folderPath, String fileName) {
            File folder = new File(folderPath);
            File file = new File(folder, fileName);
            return file.exists();
    }

    public  static void  check() throws IOException {
//        Repository repository = new FileRepository("/path/to/your/local/git/clone");
//        Remote refspec = repository.getRemote("origin");
//        příslib.getRefFactory().newRefSpec("refs/heads/*");
//        WatchListener listener = new WatchListener() {
//            @Override
//            public void onWatchedEvent(WatchEvent event) {
//                if (event.getType() == WatchEvent.Type.CREATE || event.getType() == WatchEvent.Type.MODIFY) {
//                    System.out.println("Detected push to GitLab");
//                    // 这里可以添加处理代码，比如拉取最新代码等
//                }
//            }
//        };
//        repository.getRepositoryBuilder().set advertisedReferencesAdvertisement(true);
//        repository.listen().addWatchCallback(listener);
    }
public static void main(String[] args) throws Exception {
    String folderPath = "C:\\home\\ubuntu\\java_project\\static\\q8\\public";  // 替换为实际的文件夹路径
    String fileName = "logo-0811.svg";  // 替换为要检查的文件名

    boolean exists = checkFileExistsInFolder(folderPath, fileName);
    if (exists) {
        System.out.println("文件存在");
    } else {
        System.out.println("文件不存在");
    }
}




        /**
         * 压缩
         */

        public static void zip(String input, String output, String name) throws Exception {
            //要生成的压缩文件
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output));
            String[] paths = input.split("\\|");
            File[] files = new File[paths.length];
            byte[] buffer = new byte[1024];
            for (int i = 0; i < paths.length; i++) {
                files[i] = new File(paths[i]);
            }
            for (int i = 0; i < files.length; i++) {
                FileInputStream fis = new FileInputStream(files[i]);
                if (files.length == 1 && name != null) {
                    out.putNextEntry(new ZipEntry(name));
                } else {
                    out.putNextEntry(new ZipEntry(files[i].getName()));
                }
                int len;
                // 读入需要下载的文件的内容，打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
            out.close();
        }
    /**
     * zip解压
     * @param inputFile 待解压文件名
     * @param destDirPath  解压路径
     */

    public static void ZipUncompress(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序，先打开的后关闭
                bos.close();
                out.close();
            }
        }
    }

    /**
     * @param name 压缩文件名，可以写为null保持默认
     */
    //递归压缩
    public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        //如果路径为目录（文件夹）
        if (input.isDirectory()) {
            //取出文件夹中的文件（或子文件夹）
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入
            {
                out.putNextEntry(new ZipEntry(name + "/"));
            } else//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, bos, flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
        {
            out.putNextEntry(new ZipEntry(name));
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            int len=-1;
            //将源文件写入到zip文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf,0,len);
            }
            bis.close();
            fos.close();
        }
    }
    public static void ZipCompress(String inputFile, String outputFile) throws Exception {
        //创建zip输出流
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
        //创建缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(out);
        File input = new File(inputFile);
        compress(out, bos, input,null);
        bos.close();
        out.close();
    }

    public static Map<String, Integer> sortMap(Map<String, Integer> map) {
        //利用Map的entrySet方法，转化为list进行排序
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
        //利用Collections的sort方法对list排序
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //正序排列，倒序反过来
                return o1.getValue() - o2.getValue();
            }
        });
        //遍历排序好的list，一定要放进LinkedHashMap，因为只有LinkedHashMap是根据插入顺序进行存储
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String,Integer> e : entryList
        ) {
            linkedHashMap.put(e.getKey(),e.getValue());
        }
        return linkedHashMap;
    }
}
